class BorrowingsController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem
  # If you want "remember me" functionality, add this before_filter to Application Controller
  before_filter :login_admin_required

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list

    @borrowing_pages, @borrowings = paginate(:borrowings, :per_page => 5,
                                  :conditions => @conditions, :order => 'borrowing_date DESC')
  end

  def show
    @borrowing = Borrowing.find(params[:id])
  end

  def new
    @borrowing = Borrowing.new
    @borrowing.borrowing_date = Date.today
    if !params[:book_id].nil?
      @borrowing.book_id = params[:book_id]
    end
    if !params[:user_id].nil?
      @borrowing.user_id = params[:user_id]
    end

  end

  def create
      @borrowing = Borrowing.new(params[:borrowing])
      @borrowing.state = Borrowing::STATE_BORROWED
      @book = Book.find(@borrowing.book_id)
      if @book.state == Book::STATE_AVAILABLE && @book.update_attribute(:state, Book::STATE_BORROWED) && @borrowing.save
        flash[:notice] = 'Borrowing was successfully created.'
        redirect_to :action => 'list'
      else
        flash[:warning] = 'Borrowing cannot be created.'
        render :action => 'new'
      end
  end

  def edit
    @borrowing = Borrowing.find(params[:id])
  end

  def update
    @borrowing = Borrowing.find(params[:id])
    if @borrowing.update_attributes(params[:borrowing])
      flash[:notice] = 'Borrowing was successfully updated.'
      redirect_to :action => 'show', :id => @borrowing
    else
      render :action => 'edit'
    end
  end

  def showreturn
    @borrowing = Borrowing.find(params[:id])
    @borrowing.returned_date = Date.today
  end

  def returnback
      @borrowing = Borrowing.find(params[:id])
      @borrowing.state = Borrowing::STATE_RETURNED
      @book = Book.find(@borrowing.book_id)
      if @book.state == Book::STATE_BORROWED && @borrowing.update_attributes(params[:borrowing]) && @book.update_attribute(:state, Book::STATE_AVAILABLE)
        flash[:notice] = 'Borrowing was successfully returned.'
        redirect_to :action => 'index', :id => @borrowing
      else
        flash[:waring]= 'Borrowing cannot be returned.'
        render :action => 'showreturn'
      end
  end


  def destroy
    @borrowing = Borrowing.find(params[:id])
    @book = Book.find(@borrowing.book_id)
    if @book.update_attribute(:state, Book::STATE_AVAILABLE) && @borrowing.destroy
        flash[:notice] = 'Borrowing was successfully destroyed.'
    else
        flash[:waring]= 'Borrowing cannot be destroyed.'
    end
    redirect_to :action => 'list'
  end
end
